define([
    "underscore",
    "backbone",
    "common",
    "text!html/global/menu.html"
], function (_, Backbone, common, html) {
    'use strict';

    var view = null;

    var init = function (page) {
        if (view == null) {
            view = new PageView(page);
        }
        else {
            view.render();
        }
    };

    var PageView =  Backbone.View.extend({
        id: "menu",
        className: "common",
        events: function () {
            var evtObj = {};
            evtObj["click #back"] = this.backClick;
            return evtObj;
        },
        initialize: function (options) {
            this.options = options;
            this.model = options.pageJson;
            this.createDom(html);
            this.listenTo(common.localModel.user, "change", this.userChange);
            this.listenTo(common.localModel.serverTime, "change", this.timeChange);
        },
        backClick: function () {
            if (this.options.pageback) {
                console.log(JSON.stringify(this.model));
                this.options.pageback();
            }
        },
        getModel: function () {
            return {
                name: common.localModel.user.toJSON().name || "menu",
                time: common.localModel.serverTime || this.model.pageJson.serverTime
            }
        },
        createDom: function (tpl) {
            this.remove();
            this.tpl = _.template(tpl);
            $(this.mainId).append(this.render().el);
        },
        userChange: function () {
            this.render();
            console.log("common.localModel.user:", common.localModel.user.toJSON());
        },
        timeChange: function () {
            this.render();
            console.log("common.localModel.serverTime:", common.localModel.serverTime);
        }
    });
    return {
        init: function () {
            init(this);
        },
        remove: function () {
            if (view) {
                view.remove();
                view = null;
            }
        },
    };
});